package com.zilue.payment;

import com.zilue.balance.domain.UserAccount;
import com.zilue.balance.returnresult.Result;
import com.zilue.payment.gateway.method.remote.UserAccountRemote;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.UUID;

/**
 * Created by ZD on 2017/5/22.
 */

@RestController
@SpringBootApplication
@EnableTransactionManagement
@EnableEurekaClient
@EnableFeignClients
@MapperScan("com.zilue.payment.gateway.mapper")
public class Application {
    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private UserAccountRemote userAccountRemote;

    @RequestMapping("/")
    public String index(){
        return "Hello Payment! -HFPay";
    }

    @RequestMapping("/discovery")
    public String doDiscoveryService(){
        StringBuilder buf = new StringBuilder();
        List<String> serviceIds = discoveryClient.getServices();
        if(!CollectionUtils.isEmpty(serviceIds)){
            for(String s : serviceIds){
                System.out.println("serviceId:" + s);
                List<ServiceInstance> serviceInstances =  discoveryClient.getInstances(s);
                if(!CollectionUtils.isEmpty(serviceInstances)){
                    for(ServiceInstance si:serviceInstances){
                        buf.append("["+si.getServiceId() +" host=" +si.getHost()+" port="+si.getPort()+" uri="+si.getUri()+"]");
                    }
                }else{
                    buf.append("no service.");
                }
            }
        }
        return buf.toString();
    }
    @RequestMapping(value = "/getUser",produces = "application/json")
    @ResponseBody
    public Result<UserAccount> getUser(){
        Result<UserAccount> result = userAccountRemote.getUser(UUID.randomUUID().toString(), 1);
        return result;

    }


    @RequestMapping("/getInfo")
    public String getInfo(){
        return userAccountRemote.getInfo(UUID.randomUUID().toString(),1);
    }

    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }
}
